package com.campus.backend.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.campus.backend.bean.pointsrecord.PointsRecordQueryParam;
import com.campus.backend.entity.PointsRecord;
import com.campus.backend.mapper.PointsRecordMapper;
import com.campus.backend.vo.pointsrecord.PointsRecordVo;
import com.campus.common.bean.common.PageUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 积分记录表 服务实现类
 * </p>
 *
 * @author ZhaoYuJie
 * @since 2025-05-21
 */
@Service
public class PointsRecordService extends ServiceImpl<PointsRecordMapper, PointsRecord> {

    /**
     * 分页查询积分记录列表
     *
     * @param param 查询参数
     * @return 分页结果
     */
    public PageInfo<PointsRecordVo> getPointsRecordListPage(PointsRecordQueryParam param) {
        PageInfo<PointsRecord> pageInfo = PageHelper.startPage(param.getPageNo(), param.getPageSize())
                .doSelectPageInfo(() -> this.getPointsRecordDataList(param));

        // 转换为VO对象
        List<PointsRecordVo> voList = pageInfo.getList().stream().map(pointsRecord -> {
            PointsRecordVo vo = new PointsRecordVo();
            BeanUtil.copyProperties(pointsRecord, vo);
            return vo;
        }).collect(Collectors.toList());

        return PageUtil.convertPageInfo(pageInfo, voList);
    }

    private List<PointsRecord> getPointsRecordDataList(PointsRecordQueryParam param) {
        LambdaQueryWrapper<PointsRecord> queryWrapper = new LambdaQueryWrapper<>();
        
        // 用户手机号模糊查询
        if (StrUtil.isNotBlank(param.getUserPhone())) {
            queryWrapper.like(PointsRecord::getUserPhone, param.getUserPhone());
        }
        
        // 类型
        if (param.getType() != null) {
            queryWrapper.eq(PointsRecord::getType, param.getType());
        }
        
        // 来源
        if (StrUtil.isNotBlank(param.getSource())) {
            queryWrapper.eq(PointsRecord::getSource, param.getSource());
        }
        
        // 按创建时间倒序
        queryWrapper.orderByDesc(PointsRecord::getCreateTime);
        
        return this.list(queryWrapper);
    }
}
